<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow" style="margin-top: 15px">
        <div>
          <a-form size="small" ref="formRef" :model="pageData" layout="inline">
            <CorporateSectorCascader
              ref="corPor"
              :configCascader="configCascader"
              @changeCascader="changeCascader"
            />
            <a-form-item
              field="warehouseId"
              label="仓库"
              label-col-flex="70px"
              :validate-trigger="['change', 'blur']"
              :rules="[{ required: true, message: '仓库必填' }]"
            >
              <a-select
                style="width: 200px"
                class="bacClass"
                v-model="pageData.warehouseId"
                allow-clear
                @press-enter="huiche"
              >
                <a-option v-for="item in fhWhList" :key="item" :value="item.id">
                  {{ item.warehouseName }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item field="customName" label="客户" label-col-flex="70px">
              <a-select
                style="width: 213px"
                class="bacClass"
                v-model="pageData.customName"
                allow-clear
                allow-search
                @press-enter="huiche"
                @focus="nameQuery()"
                @search="nameQuery()"
              >
                <a-option v-for="item in pageData.nameList" :key="item" :value="item.brandName">
                  {{ item.brandName }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item
              field="outInTypeName"
              label="单据类型"
              label-col-flex="70px"
              :validate-trigger="['change', 'blur']"
              :rules="[{ required: true, message: '单据类型必填' }]"
            >
              <a-select
                allow-clear
                style="width: 178px"
                class="bacClass"
                v-model="pageData.outInTypeName"
                @press-enter="huiche"
              >
                <a-option :value="0">全部</a-option>
                <a-option :value="1">入库单</a-option>
                <a-option :value="2">出库单</a-option>
              </a-select>
            </a-form-item>
            <a-form-item field="stockCode" label="单号" label-col-flex="70px">
              <a-input
                allow-clear
                style="width: 212px"
                class="bacClass"
                v-model="pageData.stockCode"
                @press-enter="huiche"
              />
            </a-form-item>
            <a-form-item field="stockTypeName" label="出入类型" label-col-flex="70px">
              <a-select
                allow-clear
                style="width: 188px"
                class="bacClass"
                v-model="pageData.stockTypeName"
                @press-enter="huiche"
              >
                <a-option>织造入库</a-option>
                <a-option>调拨入库</a-option>
                <a-option>染厂退库</a-option>
                <a-option>织造入次</a-option>
                <a-option>加工出库</a-option>
                <a-option>调拨出库</a-option>
                <a-option>销售出库</a-option>
                <a-option>其他出库</a-option>
              </a-select>
            </a-form-item>
            <a-form-item field="stockDate" label="日期" label-col-flex="70px">
              <a-range-picker style="width: 285px" class="bacClass" v-model="pageData.stockDate" />
            </a-form-item>
          </a-form>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <Toolbar
          class="gesture"
          :items="[
            `${permissionStore.hasPermisson('pbjccfycx.cx') ? '查询' : ''}`,
            `${permissionStore.hasPermisson('pbjccfycx.dc') ? '全部导出' : ''}`,
          ]"
          @select="selectHandler"
          @exportAll="exportAlls"
        ></Toolbar>
      </div>
    </template>
    <template #pageTabel>
      <a-spin
        :loading="pageData.pageLoading"
        tip="加载中"
        dot
        style="height: 100%; width: 100%; z-index: 999"
      >
        <AgGridVuesCopys
          :rowHeight="33"
          :headerHeight="33"
          rowSelection="multiple"
          @grid-ready="gridReady"
          style="height: 100%"
          :defaultColDef="defaultColDef"
          :suppressCopyRowsToClipboard="true"
          class="ag-theme-alpine"
          :rowData="pageData.dataList"
          :columnDefs="tableColumns"
          :localeText="localeText1"
          @FilterChanged="FilterChangeds"
        >
        </AgGridVuesCopys>
      </a-spin>
    </template>
    <paginationCopys
      :page-size-options="pagingList1"
      :total="total"
      :page-size="size"
      :current="page"
      show-total
      show-jumper
      show-page-size
      @change="PageSize"
      @page-size-change="change1"
      style="justify-content: center"
    />
  </pageTabelLayout>
</template>

<script lang="ts" setup>
import { post, get } from '@/api/http'
import emitter from '@/hooks/useEventBus'
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import PageTabelLayout from '@/components/pageTabelLayout.vue'
import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import WHService from '@/service/wh'
import { assTable } from '@/utils/assemblyLevelTable'
import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
import dayjs from 'dayjs'
import usePermission from '@/store/modules/permission'
import filedownload from 'js-file-download'
import setTableTotalRow from '@/utils/setTableTotalRow.ts'
const pagingList1: any = ref(pagingList)
const localeText1: any = ref(localeText)
const headerShow = ref<boolean>(true)
const permissionStore = usePermission()
const pageData: any = reactive({
  pageLoading: false,
  companyId: null,
  warehouseId: null,
  nameList: [],
})

const defaultColDef: any = {
  sortable: true,
  resizable: true,
  filter: true,
}
const gridOption = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api
}

const tableColumns: any = [
  { headerName: '公司', field: 'companyName', width: 150 },
  { headerName: '仓库', field: 'warehouseName', width: 150 },
  { headerName: '客户', field: 'customName', width: 150 },
  { headerName: '单据类型', field: 'stockTypeName', width: 150 },
  { headerName: '单号', field: 'stockCode', width: 150 },
  { headerName: '客户订单号', field: 'customOrderCode', width: 150 },
  { headerName: '出入类型', field: 'outInTypeName', width: 150 },
  { headerName: '织布单号', field: 'planOrderCode', width: 150 },
  { headerName: '坯布编号', field: 'greyCode', width: 150 },
  { headerName: '坯布名称', field: 'greyName', width: 150 },
  { headerName: '纱批', field: 'yarnBatch', width: 150 },
  { headerName: '指令重量', field: 'orderWeight', width: 150 },
  { headerName: '匹数', field: 'horseNum', width: 150 },
  { headerName: '重量', field: 'weight', width: 150 },
  { headerName: '加工单价', field: 'price', width: 150 },
  { headerName: '金额', field: 'amount', width: 150 },
  { headerName: '制版费', field: 'showMakeEditionCost', width: 150 },
  { headerName: '备注', field: 'remark', width: 150 },
  { headerName: '开单日期', field: 'stockDate', width: 150 },
]

//分页
const total = ref(0)
const page = ref(1)
const size = ref(10)
function PageSize(val: any) {
  page.value = val
  doRefresh()
}
function change1(val: any) {
  size.value = val
  doRefresh()
}

//查询
const formRef: any = ref()
function doRefresh() {
  formRef.value?.validate().then((err: any) => {
    if (!err) {
      pageData.pageLoading = true
      post({
        url: '/wms/GreyStockIn/getGreyStockOutInReport',
        data: {
          page: page.value,
          size: size.value,
          companyId: pageData.companyId,
          warehouseId: pageData.warehouseId,
          customName: pageData.customName,
          stockTypeName: pageData.stockTypeName,
          stockCode: pageData.stockCode,
          outInTypeName: pageData.outInTypeName == 0 ? '' : pageData.outInTypeName,
          beginDate: pageData.stockDate ? pageData.stockDate[0] : '',
          endDate: pageData.stockDate ? pageData.stockDate[1] : '',
        },
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            pageData.tableList = data.listc
            gridOption.value.setRowData(data.list)
            setTableTotalRow(gridOption, data.list, ['horseNum', 'weight', 'amount'])
            total.value = data.total
          }
        })
        .catch(console.log)
        .finally(() => {
          pageData.pageLoading = false
        })
    }
  })
}

const selectHandler = () => {
  page.value = 1
  doRefresh()
}

const huiche = () => {
  doRefresh()
}

//公司 仓库
const corPor: any = ref()
const whService = new WHService()
const fhWhList: any = whService.whList
const configCascader = ref<{}>({
  corporateWidth: '200px', //公司宽度
  corporateRquired: true, //公司是否必填
  size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
  corporateName: '公司', //公司label
  cascaderShow: 'sector', //配置部门不显示
  corporateNameLabelWidth: '70px',
})

const changeCascader = (data: any) => {
  const { corporateId, corporateLabel } = data
  pageData.companyId = corporateId
  if (pageData.companyId) {
    whService.getWarhouseListByFirmId(corporateId, '坯布仓')
  }
}

const nameQuery = () => {
  post({
    url: '/product/Brand/getFieldValue',
    data: {
      brandName: pageData.customName ? pageData.customName : '',
    },
  }).then(({ data, code }: any) => {
    if (code === 200) {
      pageData.nameList = data
    }
  })
}

const exportAlls = () => {
  post({
    url: '/wms/GreyStockIn/exportGreyStockOutInReport',
    data: {
      companyId: pageData.companyId,
      warehouseId: pageData.warehouseId,
      customName: pageData.customName,
      stockTypeName: pageData.stockTypeName,
      stockCode: pageData.stockCode,
      outInTypeName: pageData.outInTypeName == 0 ? '' : pageData.outInTypeName,
      beginDate: pageData.stockDate ? pageData.stockDate[0] : '',
      endDate: pageData.stockDate ? pageData.stockDate[1] : '',
    },
    responseType: 'blob',
  }).then((res: any) => {
    filedownload(res, '坯布进出仓单费用查询.xlsx')
  })
}

const FilterChangeds = (params: any) => {
  let data: any = {
    list: [],
  }
  params.api.forEachNodeAfterFilter((row: any) => {
    data.list.push(row.data)
  })
  setTableTotalRow(gridOption, data.list, ['horseNum', 'weight', 'amount'])
}

onMounted(() => {
  pageData.rHeight = document.getElementsByClassName('main-section')[0]?.clientHeight
  //弹出层的高
  if (pageData.rHeight !== undefined) {
    pageData.rHeight = pageData.rHeight
  }
  pageData.outInTypeName = 0
  pageData.stockDate = [
    dayjs(new Date()).format('YYYY-MM-DD'),
    dayjs(new Date()).format('YYYY-MM-DD'),
  ]
})
</script>
<style scoped>
:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}

:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}
</style>